package com.lj.demo.springbootshirojwt.filter;

import com.google.common.collect.Maps;
import com.lj.demo.springbootshirojwt.util.Constants;
import com.lj.demo.springbootshirojwt.util.HttpRequestUtil;
import com.lj.demo.springbootshirojwt.util.JWTToken;
import org.apache.shiro.web.filter.authc.BasicHttpAuthenticationFilter;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.util.StringUtils;

import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import javax.servlet.http.HttpServletRequest;
import java.util.Map;

/**
 * Title: JWT过滤器
 * Description:
 * Date: 2019年06月26日 9:52
 *
 * @author lvjie@hiynn.com
 * @version 1.0
 * Significant Modify：
 * Date                  Author                 Content
 * =================================================================
 * 2019年06月26日         lvjie@hiynn.com         创建文件,实现基本功能
 * =================================================================
 */
public class JwtFilter extends BasicHttpAuthenticationFilter {

    private static final Logger LOGGER = LoggerFactory.getLogger(BasicHttpAuthenticationFilter.class);

    @Override
    protected boolean isAccessAllowed(ServletRequest request, ServletResponse response, Object mappedValue) {
        try {
           if (StringUtils.isEmpty(HttpRequestUtil.getTokenFromRequest((HttpServletRequest) request))){
               //错误提示仅限demo演示
               Map<String, String> map = Maps.newLinkedHashMapWithExpectedSize(3);
               map.put("code", "-1");
               map.put("message", "fail");
               map.put("result", "token不能为空redis");
               response.setCharacterEncoding("utf-8");
               response.getWriter().print(Constants.COMM_GSON.toJson(map));
           }
            //放行跨域options试探请求
           if (!Constants.REQUEST_CROS_METHOD.equalsIgnoreCase(((HttpServletRequest) request).getMethod())){
               //执行登录
               executeLogin(request,response);
           }
       }catch (Exception e){
            LOGGER.error("登录失败：",e);
       }
        return true;
    }



    @Override
    protected boolean executeLogin(ServletRequest request, ServletResponse response) throws Exception {
        String token = HttpRequestUtil.getTokenFromRequest((HttpServletRequest) request);
        JWTToken jwtToken = new JWTToken(token);
        getSubject(request,response).login(jwtToken);
        return true;
    }
}
